Scala for the Impatient by Horstmann Cay S

Scala for the Impatient by Horstmann Cay S

Author:Horstmann, Cay S. [Horstmann, Cay S.]
Language: eng
Format: epub, azw3, pdf
Publisher: Pearson Education
Published: 2012-03-08T00:00:00+00:00


14.6 Extractors

In the preceding section, you have seen how patterns can match arrays, lists, and tuples. These capabilities are provided by extractors—objects with an unapply or unapplySeq method that extract values from an object. The implementation of these methods is covered in Chapter 11. The unapply method is provided to extract a fixed number of objects, while unapplySeq extracts a sequence whose length can vary.

For example, consider the expression

arr match {

case Array(0, x) => ...

...

}

The Array companion object is an extractor—it defines an unapplySeq method. That method is called with the expression that is being matched, not with what appears to be the parameters in the pattern. The call Array.unapplySeq(arr) yields a sequence of values, namely the values in the array. The first value is compared with zero, and the second one is assigned to x.

Regular expressions provide another good use of extractors. When a regular expression has groups, you can match each group with an extractor pattern. For example:

val pattern = "([0-9]+) ([a-z]+)".r

"99 bottles" match {

case pattern(num, item) => ...

// Sets num to "99", item to "bottles"

}

The call pattern.unapplySeq("99 bottles") yields a sequence of strings that match the groups. These are assigned to the variables num and item.

Note that here the extractor isn’t a companion object but a regular expression object.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.